package com.bw.cinema.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.cinema.intent.MutilTypeIntent
import com.bw.cinema.service.MutilTypeService
import com.bw.cinema.state.MutilTypeState
import com.bw.lib_mvi.viewmodel.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class MutilTypeViewModel : BaseViewModel<MutilTypeIntent>() {
    private val service: MutilTypeService by lazy { MutilTypeService() }

    private val _state = MutableStateFlow<MutilTypeState>(MutilTypeState.init)
    val state: StateFlow<MutilTypeState>
        get() = _state

    override fun handlerIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it) {

                    is MutilTypeIntent.getMutilType -> {
                        doMutilType(it)
                    }

                    is MutilTypeIntent.getSubMutilType -> {
                        doSubMutilType(it)
                    }

                    else -> {}
                }
            }
        }
    }

    private fun doSubMutilType(it: MutilTypeIntent.getSubMutilType) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.getSubMutilType(it.id)
            if (data.code == 0) {
                _state.value = MutilTypeState.getSubMutilTypeState(data.data)
            } else {
                _state.value = MutilTypeState.Failed
            }
        }
    }

    private fun doMutilType(it: MutilTypeIntent.getMutilType) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.getMutilType()
            if (data.code == 0) {
                _state.value = MutilTypeState.getMutilTypeState(data.data)
            } else {
                _state.value = MutilTypeState.Failed
            }
        }
    }
}